import { getSearchKeyWords, getSearchRecommendDatas, getSearchDatas } from '@/api/search.js'
import { Message } from 'element-ui'
import tool from '@/utils/tool'
export default {
  namespaced: true,
  name: 'search',
  state: ()=>({
    // 搜索数据
    searchDatas: [],
    pager: {
      cp: 1,
      ps: 10,
      total: 0
    },
    // 搜索推荐数据
    recommendDatas: {
      // 底部资讯
      news: [],
      // 推荐商品和直播
      course_live: {},
      // 智能题库
      exams: [],
      profession_id: ''
    },
    // 搜索词列表
    keyWords: [],
  }),
  mutations: {
    // 获取搜索数据
    setSearchDatas(state, data) {
      state.searchDatas = data.hits
      state.pager.total = data.total
    },
    // 搜索推荐数据
    setRecommendDatas(state, data) {
      state.recommendDatas = data
    },
    // 获取搜索此列表
    setKeywods(state, data) {
      state.keyWords = tool.encodeString(data) 
    }
  },
  actions: {
    // 获取搜索数据
    async getSearchDatas({ state, commit, rootState }, params) {
      state.pager.cp = params.cp || 1
      params = { ...params, ...state.pager }
      let res = await getSearchDatas(params).catch(err => {
        return {
          data: {
            hits: [],
            total: 0
          }
        }
      })
      let { errcode, errmsg } = res

      if (errcode !== 0) {
        Message({ type: 'warning', message: errmsg })
        res = {
          data: {
            hits: [],
            total: 0
          }
        }
      }
      commit('setSearchDatas', res.data)
    },
    // 获取推荐信息
    async getRecommendDatas({ state, commit, rootstate }, params) {
      let res = await getSearchRecommendDatas(params).catch(err => {
        return {
          data: {
            // 底部资讯
            news: [],
            // 推荐商品和直播
            course_live: {},
            // 智能题库
            exams: [],
          }
        }
      })
      commit('setRecommendDatas', res.data)
    },
    // 获取搜索词列表
    async getSearchKeyWords({ state, commit, rootState }, params) {
      // 获取热搜缓存
      let { keywods, cacheStamp } = localStorage.getItem('search_key_words') ? JSON.parse(localStorage.getItem('search_key_words')) : {}
      let currentDateStamp = Date.now()
      if (keywods) {  //存在缓存
        if (cacheStamp > currentDateStamp) {  //未过期
          commit('setKeywods', keywods)
          return
        } else {
          localStorage.removeItem('search_key_words')
        }
      }
      let res = await getSearchKeyWords(params).catch(err => {
        return {
          data: []
        }
      })
      commit('setKeywods', res.data)
      // 设置缓存时间1天
      let cacheTime = 1000 * 60 * 60 * 24
      let search_key_words = JSON.stringify({ keywods: res.data, cacheStamp: cacheTime + currentDateStamp })
      localStorage.setItem('search_key_words', search_key_words)
    }
  },
  getters: {}
}
